    //
//  TwitterAuthorizeViewController.m
//  mytcom
//
//  Created by Le Lam on 2/17/11.
//  Copyright 2011 Seta:Cinq VN. All rights reserved.
//

#import "TwitterViewController.h"
#import "TwitterHelper.h"

@implementation TwitterViewController

// The designated initializer.  Override if you create the controller programmatically and want to perform customization that is not appropriate for viewDidLoad.
/*
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization.
    }
    return self;
}
*/

/*
// Implement loadView to create a view hierarchy programmatically, without using a nib.
- (void)loadView {
}
*/


// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
    [super viewDidLoad];
	
	self.title = @"Connect to Twitter";
	
	if (![TwitterHelper isAuthorized]) {
		twitter = [[TwitterHelper alloc] init];
		twitter.authorizeWebView = [[UIWebView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height - self.navigationController.navigationBar.frame.size.height)];
		[self.view addSubview:twitter.authorizeWebView];
		
		[self performSelector:@selector(authorize) withObject:nil afterDelay:0.15];
	} else {
		UIActivityIndicatorView *loading = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge] autorelease];
		loading.center = CGPointMake(self.view.frame.size.width / 2, self.view.frame.size.height / 2);
		[loading startAnimating];
		
		[self.view addSubview:loading];
		
		[self.view setNeedsDisplay];

		[self performSelector:@selector(logout) withObject:nil afterDelay:0.5];
	}

}

- (void)authorize {
	[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(twitterDidAuthorize:) name:kTwitterDidAuthorize object:nil];
	[twitter authorize];
}

- (void)twitterDidAuthorize:(NSNotification *)notification {
	[[NSNotificationCenter defaultCenter] removeObserver:self name:kTwitterDidAuthorize object:nil];

	[self.navigationController popViewControllerAnimated:YES];
}


- (void)didReceiveMemoryWarning {
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc. that aren't in use.
}

- (void)viewDidUnload {
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}


- (void)dealloc {
	[twitter release];
    [super dealloc];
}

- (void)logout {
	[TwitterHelper deleteCredential];
	[self.navigationController popViewControllerAnimated:YES];		
}

@end
